package com.gexin.controller.xapp.product;


import com.gexin.common.utils.StringUtil;
import com.gexin.controller.system.LoginController;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.model.order.*;
import com.gexin.model.product.Products;
import com.gexin.model.system.AdminConfig;
import com.gexin.model.template.TemplateArea;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.memberAcitivty.IntegralService;
import com.gexin.service.user.UserService;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单接口
 *
 * @author 肖得明
 */
@Before(XAppSafeInterceptor.class)//统一错误拦截
@ControllerBind(controllerKey = "/xapp/order")
public class OrderController extends AppController {
	static Log log = Log.getLog(LoginController.class);



	//完成订单接口（确认收货）
	public void finish() {
		Order o = Order.dao.findById(getPara("id"));
		if (o == null) {
			fail("订单ID不存在！");
			return;
		}
		if(o.getState()!=Order.State_Send_Express){
			fail("订单状态异常，请联系管理员");
			return;
		}

		IntegralService integralService = new IntegralService();
		integralService.buyGeneralIntegral(o);


 		if(o.getAgentId()!=null&&!(o.getRegisterOrder()!=null&&o.getRegisterOrder()==1)){
			UserAddress address = UserAddress.dao.findById(o.getAddressId());
			//调用任东岳方法
//			ApiResponse response=AgentService.dao.fashionable(o.getAgentId(),o.getAgentCityId(), o.getTotalAmount(),o.getId());

//			if(response.isState()==false){
//				log.info(" 调用任东岳 订单完成后给供应商添加金额 失败了，"+response.getMsg());
//			}else{
//				o.setAgentCashBack(new BigDecimal(response.getData().toString()).setScale(2,BigDecimal.ROUND_HALF_UP));
//			}
		}
        if(o.getIsUserHongbao()!=null&&o.getIsUserHongbao()==1){
            WeixinUser weixinUser = WeixinUser.dao.findById(o.getUserId());
            weixinUser.setIceAccount(weixinUser.getIceAccount().subtract(o.getUserHongbaoPrice()));
            UserRebate userRebate = UserRebate.dao.findFirst("select * from t_user_rebate where user_id=? and order_id=?", weixinUser.getId(), o.getId());
            userRebate.setState(1);
            userRebate.update();
        }


		AdminConfig sysConfig = AdminConfig.dao.getSysConfig();
		if(sysConfig.getOpenReward()==1){
			UserService.dao.addUserRebate(o.getUserId(),o.getId());
		}

		o.setState(Order.State_Finish);
		o.setReceiptTime(new Date());
		//判断下是否有用优惠券
		if(!StringUtils.isEmpty(o.getCouponId())){
			UserCoupon userCoupon=UserCoupon.dao.findByUserIdAndCoupon(getAuthUserId(),o.getCouponId());
			if(userCoupon!=null){
				if(userCoupon.getUseState()==99){
					userCoupon.setUseState(1);
					userCoupon.update();
				}else{
					fail("抱歉，优惠卷状态异常，请联系管理员");
					return;
				}
			}
		}

		//给经销商推送模板消息
		boolean update = o.update();



		success();
	}
	//关闭订单接口
	public void close() {
		Order o = Order.dao.findById(getPara("id"));
		if (o == null) {
			fail("订单ID不存在！");
			return;
		}
		if (o.getState() != Order.State_Wait_Pay) {
			fail("订单状态不是待支付！");
			return;
		}
		o.setState(Order.State_Close);
		//判断下是否有用优惠券
		if(!StringUtils.isEmpty(o.getCouponId())){
			UserCoupon userCoupon=UserCoupon.dao.findByUserIdAndCoupon(getAuthUserId(),o.getCouponId());
			if(userCoupon!=null){
				if(userCoupon.getUseState()==99){
					userCoupon.setUseState(0);
					userCoupon.update();
				}else{
					fail("抱歉，优惠卷状态异常，请联系管理员");
					return;
				}
			}
		}
		o.update();
		success();
	}

	public void list() {
		Integer state = getParaToInt("state");
//		Integer type= getParaToInt("type");
		System.out.println(getAuthUserId());
		StringBuffer sql = new StringBuffer("SELECT id,total_amount,express_amount,createtime,state,type,cash_coupon from  t_order  where user_id=" + getAuthUserId());
		if (state != null) {
			sql.append(" and state=" + state);
		}
//		if(type!=null){
//			sql.append(" and type = "+type);
//		}
		sql.append(" order by createtime desc   limit ?,?");
		List<Order> list = Order.dao.find(sql.toString(), (getPageIndex()-1)*getPageSize(),getPageSize());
		for (Order order : list) {
			OrderState orderState= OrderState.dao.findFirst(" select * from t_order_state where state_id = ?  ",order.getState());
			if(orderState!=null){
				if(order.getType()==2){
					OrderPresale is_sf=OrderPresale.dao.findByOrderIdAndType(order.getId(),1);//查订金
					OrderPresale is_wk=OrderPresale.dao.findByOrderIdAndType(order.getId(),2);//查尾款
					if(is_sf.getState()==1){
						order.put("state_name","待支付定金");
						order.put("is_presale_state",1);
					}else if(is_sf.getState()==2 && is_wk.getState()==1){
						order.put("state_name","待支付尾款");
						order.put("is_presale_state",2);
					}else{
						order.put("state_name",orderState.getStateName());
						order.put("is_presale_state",3);
					}
					order.put("earnest_charge_money",is_sf.getMoney());
					order.put("tail_charge_money",is_wk.getMoney());
				}else{
					order.put("state_name",orderState.getStateName());
					order.put("is_presale_state",0);
				}
			}else{
				order.put("state_name","订单状态异常("+order.getState()+")");
				order.put("is_presale_state",0);
			}


			List<OrderItem> detail_list= OrderItem.dao.getItembyId(order.getId());
			for(OrderItem item:detail_list){
			 	order.put("refund_status",item.getRefundState());
			}
			order.put("detail",detail_list );
			//新增优惠卷
			if(!StringUtils.isEmpty(order.getCouponId())){
				UserCoupon userCoupon=UserCoupon.dao.findById(order.getCouponId());
				if(userCoupon!=null){
					order.put("coupons",userCoupon);
				}else{
					order.put("coupons",null);
				}
			}else{
				order.put("coupons",null);
			}
		}
		if (list.size() > 0) {
			success(list);
		} else {
			fail("no data");
		}
	}

	public void detail() {
		String order_id = getPara("order_id");
		if (StringUtil.isBlank(order_id)) {
			fail("订单编号不能为空");
			return;
		}
		Order order = Order.dao.findById(order_id);
		if(order==null){
			fail("订单不存在！");
			return;
		}
		//新增优惠卷
		if(!StringUtils.isEmpty(order.getCouponId())){
			UserCoupon userCoupon=UserCoupon.dao.findById(order.getCouponId());
			if(userCoupon!=null){
				order.put("coupons",userCoupon);
			}else{
				order.put("coupons",null);
			}
		}else{
			order.put("coupons",null);
		}
		OrderState orderState= OrderState.dao.findFirst(" select * from t_order_state where state_id = ?  ",order.getState());
		if(orderState!=null) {
			if (order.getType() == 2) {
				OrderPresale is_sf = OrderPresale.dao.findByOrderIdAndType(order.getId(), 1);//查订金
				OrderPresale is_wk = OrderPresale.dao.findByOrderIdAndType(order.getId(), 2);//查尾款
				if (is_sf.getState() == 1) {
					order.put("state_name", "待支付定金");
					order.put("is_presale_state", 1);
				} else if (is_sf.getState() == 2 && is_wk.getState() == 1) {
					order.put("state_name", "待支付尾款");
					order.put("is_presale_state", 2);
				} else {
					order.put("state_name", orderState.getStateName());
					order.put("is_presale_state", 3);
				}
				order.put("earnest_charge_money",is_sf.getMoney());
				order.put("tail_charge_money",is_wk.getMoney());
			} else {
				order.put("state_name", orderState.getStateName());
				order.put("is_presale_state", 0);
			}
		}else{
			order.put("state_name","订单状态异常("+order.getState()+")");
			order.put("is_presale_state",0);
		}
		/*if(!order.getUserId().equals(getAuthUserId())){
			fail("非法访问！");
			return ;
		}*/
		List<OrderItem> order_item=OrderItem.dao.getItembyId(order.getId());
		for(OrderItem item:order_item){
			Products products =Products.dao.findById(item.getProductId());
			item.put("products_tail_pay_time", products.getTailPayTime());
			item.put("buy_count_post_fee", products.getBuyCountPostFee());
			//返回每个商品的运费给小袁袁
			UserAddress address = UserAddress.dao.findById(order.getAddressId());
			int template_id = products.getTemplateId() == null ? 0 : products.getTemplateId();
			BigDecimal post_fee = new BigDecimal(0);
			if (template_id != 0 && address != null && TemplateArea.dao.getAreaState(template_id, address.getCountyId()+"")) {
				post_fee = TemplateArea.dao.trans_fee(item.getNums(), template_id, address.getCountyId()+"");
			} else if (products.getPostFee().doubleValue() > 0) { // 判断运费大于0的时候
				post_fee = products.getPostFee();
			}
			item.put("real_fee",post_fee);
			order.put("refund_status",item.getRefundState());
		}
		order.put("detail", order_item);
		//黎峻加的物流字段
		order.put("express", OrderExpress.dao.cache_getProductOrderExpressByOrderId(order_id));
		success(order);
	}



	//创建订单 当用户选完参数的时候 创建一个失效订单
	public void create(){
		Integer product_id =getParaToInt("product_id");
		Integer buy_count =getParaToInt("buy_count");
		String sku_id =getPara("sku_id");

		Products products =Products.dao.findById(product_id);
		if(products==null || products.getOnlineState()!=1){
			fail("抱歉，此商品不存在或已删除");
			return;
		}

	}


}
